package com.ladybug.flow.modules.flow.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ladybug.flow.common.vo.ResponseResult;
import com.ladybug.flow.modules.flow.domain.DTO.NewModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author xianglongfei
 * @description
 * @createDate 2023/1/19 9:05
 */
@RestController
@RequestMapping("/model")
public class ModelController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 新建一个空模型
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/newModel")
    public Object newModel(@RequestBody NewModel newModel) throws UnsupportedEncodingException {
        //securityUtil.logInAs("admin");
        //初始化一个空模型
        Model model = repositoryService.newModel();

        //设置一些默认信息
        String name = newModel.getName();
        String description = newModel.getDes();
        int revision = 1;
        String key = newModel.getKey();

        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());

        repositoryService.saveModel(model);
        String id = model.getId();


        //完善ModelEditorSource
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace",
                "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.put("stencilset", stencilSetNode);
        repositoryService.addModelEditorSource(id,editorNode.toString().getBytes("utf-8"));


        return "redirect:/static/modeler.html?modelId="+id;
    }

    /**
     * 获取所有模型
     * @return
     */
    @GetMapping
    @RequestMapping("/modeList")
    public ResponseResult modelList(org.springframework.ui.Model model){
        //securityUtil.logInAs("system");
        List<Model> models = repositoryService.createModelQuery().orderByCreateTime().desc().list();
        model.addAttribute("models",models);
        return ResponseResult.success(models);
    }
}
